import asyncio
import time

now = lambda: time.time()


async def do_some_sleep_work(x):
    print('Waiting: ', x)
    # 使用 await 会让出协程占用的cpu;协程遇到await，事件循环将会挂起该协程，执行别的协程，直到其他的协程也挂起或者执行完毕，再进行下一个协程的执行
    await await_m()
    print("sleep-over:",x)
    return 'Done after {}s'.format(x)

async def await_m():
    time.sleep(10)
    print("awaiting")

async def do_some_work(x):
    print('no-Waiting: ', x)
    return 'Done after {}s'.format(x)

if __name__ == '__main__':
    start = now()

    coroutine1 = do_some_sleep_work(1)
    coroutine2 = do_some_work(2)
    loop = asyncio.get_event_loop()
    task1 = asyncio.ensure_future(coroutine1)
    task2 = asyncio.ensure_future(coroutine2)
    loop.run_until_complete(task1)
    loop.run_until_complete(task2)

    print('Task1 ret: ', task1.result())
    print('Task2 ret: ', task2.result())
    print('TIME: ', now() - start)

'''
打印的顺序是：
Waiting:  1
awaiting
sleep-over: 1
no-Waiting:  2
Task1 ret:  Done after 1s
Task2 ret:  Done after 2s
TIME:  1.0047001838684082

task1执行完 才会执行task2；并不是在task1的do_some_sleep_work方法中让出cpu，让task2执行
'''